package cn.monkey.family.server.domain.shop.order;

import cn.monkey.family.data.Range;
import cn.monkey.family.data.crud.repository.CrudRepository;
import cn.monkey.family.data.crud.repository.QueryDslQueryRequestRepository;
import cn.monkey.family.data.shop.order.Order;
import cn.monkey.family.data.shop.order.OrderQueryRequest;
import cn.monkey.family.data.shop.order.QOrder;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.types.Predicate;
import org.springframework.data.repository.NoRepositoryBean;


@NoRepositoryBean
public interface OrderRepository extends CrudRepository<Order, String>,
        QueryDslQueryRequestRepository<Order, String, OrderQueryRequest> {

    @Override
    default Predicate queryDslPredicate(OrderQueryRequest queryRequest) {
        QOrder qOrder = QOrder.order;
        String[] detailIds = queryRequest.getDetailIds();
        BooleanBuilder booleanBuilder = new BooleanBuilder();
        if (detailIds != null && detailIds.length > 0) {
            booleanBuilder.and(qOrder.details.any().in(detailIds));
        }
        Range<Long> createdTimeRange = queryRequest.getCreatedTimeRange();
        if (createdTimeRange != null) {
            Long min = createdTimeRange.getMin();
            Long max = createdTimeRange.getMax();
            if (min != null && max != null) {
                booleanBuilder.and(qOrder.createdTime.between(min, max));
            } else if (min != null) {
                booleanBuilder.and(qOrder.createdTime.gt(min));
            } else if (max != null) {
                booleanBuilder.and(qOrder.createdTime.lt(max));
            }
        }
        String[] status = queryRequest.getStatus();
        if (status != null && status.length > 0) {
            booleanBuilder.and(qOrder.status.in(status));
        }
        return booleanBuilder;
    }
}
